var chatSocket = function() {
	var output,websocket,chat=this;
	return {
		init:function() {			
		    output = $('#conversation');		    
		    chatSocket.testWebSocket();
		    localChatStore.init();
		},
		stop:function() {
			websocket.send('disconnect');
		},
		testWebSocket:function(){
			websocket = new WebSocket(wsUri);			
			websocket.onopen = function(evt) { chatSocket.onOpen(evt); };
			websocket.onclose = function(evt) { chatSocket.onClose(evt); };
			websocket.onmessage = function(evt) { chatSocket.onMessage(evt); };
			websocket.onerror = function(evt) { chatSocket.onError(evt); };
		},
		onOpen:function(evt) {
			chatSocket.writeToScreen("Connected to server");
			chatSocket.doSend("Hello are you there WebSocket Server");
		},
		onClose:function(evt) {
			chatSocket.writeToScreen("...Kaboom...Im gone");
		},
		onError:function(evt){
			chatSocket .writeToScreen(evt.data);
		},
		doSend:function(message){
			chatSocket.writeToScreen("SENT: " + message); 
			websocket.send(message);
		},
		writeToScreen:function(message, store){
			output.append(">>"+message+"<br />");
			output.attr({
		        scrollTop: $('#conversation').attr('scrollHeight')
		    });
			//default to storing the message shown
			if (store || typeof(store) == 'undefined') localChatStore.append(message);
		},
		onMessage:function(evt) {			
			var json = jQuery.parseJSON(evt.data);			
			var message = json.player + ": " + json.message;
			chatSocket.writeToScreen(message);
		}
	}
}();

var localChatStore = function() {
	var storageKey = "poker_app_chat_log",storedChat="chat";
	return {		
		init:function() {
			if(localChatStore.checkSupport) {
				storedChat = localStorage.getItem(storageKey);
				if (storedChat == null) {
					try {
						localStorage.setItem(storageKey, storedChat);
					} catch (e) {
						if (e == QUOTA_EXCEEDED_ERR) alert("Quota exceeded!");
					}					
				} else {
					localChatStore.restore(storedChat);
				}
			}
		},
		checkSupport:function() {
			if (typeof(localStorage) == 'undefined' ) {
				alert('Your browser does not support HTML5 localStorage. Try upgrading.');
				return false;
			} else return true;
		},
		restore:function(chat) {
			chat = chat.split(";");			
			for (var i = 0;i < chat.length; i++) {
				chatSocket.writeToScreen(chat[i],false);
			}
		},
		append:function(message) {
			storedChat += ";" + message;
			try {
				localStorage.setItem(storageKey, storedChat);
			} catch (e) {
				if (e == QUOTA_EXCEEDED_ERR) alert("Quota exceeded!");
			}
		}
	}
}();